package form

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"path/filepath"
	"strconv"
	"strings"
	"time"
	"yak.admin/src/entity"
	"yak.admin/src/util"
)

const DevicePageConfigKey = "@#sfesd#EDSs"

type ReportDeviceAnnexForm struct {
	Number   string `form:"number" validate:"required" chn:"报告编号"`
	Sign     string `form:"sign" validate:"required"`
	Filename string `form:"filename" validate:"required"`
}

func (form *ReportDeviceAnnexForm) Valid() error {
	if !util.VerifyMd5Sign(form.Sign, DevicePageConfigKey, form.Number) {
		return errors.New("页面配置信息有误")
	}
	return nil
}

func (form *ReportDeviceAnnexForm) UploadImageAnnex(ctx *gin.Context) (string, error) {
	folder := util.CreateDir("storage/annexes/" + time.Now().Format("2006/01/02") + "/" + form.Number)
	file, err := ctx.FormFile("file")
	if err == nil {
		if file.Size > 1024*1024*16 {
			return "", errors.New("上传素材不能大于2M")
		}
		ext, _ := util.GetImgExt(file)
		filename := filepath.Join(folder, form.Filename+ext)
		if err := ctx.SaveUploadedFile(file, filename); err == nil {
			timeUnix := time.Now().Unix()
			return filepath.ToSlash(filename[8:]) + "?" + strconv.FormatInt(timeUnix, 10), nil
		}
	}

	return "", err
}

type DeviceSubmitForm struct {
	Number              string              `form:"number" json:"number" validate:"required" chn:"报告编号"`
	CompanyName         string              `form:"company_name" json:"company_name" validate:"required" chn:"企业名称"`
	ProduceName         string              `form:"produce_name" json:"produce_name" validate:"required" chn:"产品名称"`
	ProduceNumber       string              `form:"produce_number" json:"produce_number" validate:"required" chn:"批号/型号"`
	ProduceId           string              `form:"produce_id" json:"produce_id" validate:"required" chn:"注册证号/备案号"`
	Sign                string              `form:"sign" json:"sign" validate:"required"`
	RiskDescRefer       string              `json:"risk_desc_refer"`
	RiskDescAnnexes     []map[string]string `form:"desc_annexes[]" json:"desc_annexes"`
	RiskDesc            map[int]string      `json:"risk_desc"`
	RiskAnalysis        map[int]string      `json:"risk_analysis"`
	RiskAnalysisRefer   []string            `form:"analysis_annexes_refer[]" json:"analysis_annexes_refer"`
	RiskAnalysisAnnexes []map[string]string `form:"analysis_annexes[]" json:"analysis_annexes"`
}

func (form *DeviceSubmitForm) Valid(ctx *gin.Context) error {
	if !util.VerifyMd5Sign(form.Sign, DevicePageConfigKey, form.Number) {
		return errors.New("页面配置信息有误")
	}
	return nil
}

func (form *DeviceSubmitForm) Submit(ctx *gin.Context, user entity.User) error {
	db := util.GetMysqlPool().Handler()
	fmt.Println(form.RiskAnalysisRefer)
	report := entity.DeviceReport{
		Number:            form.Number,
		CompanyName:       form.CompanyName,
		ProduceName:       form.ProduceName,
		ProduceNumber:     form.ProduceNumber,
		ProduceId:         form.ProduceId,
		ReportedAt:        time.Now().Unix(),
		Province:          user.Province,
		City:              user.City,
		County:            user.County,
		Address:           user.Address,
		Phone:             user.Phone,
		Unit:              user.Company,
		Username:          user.Username,
		Status:            util.PendingStatus,
		UserId:            user.Id,
		RiskDescRefer:     form.RiskDescRefer,
		RiskAnalysisRefer: strings.Join(form.RiskAnalysisRefer, ","),
	}

	if err := db.Create(&report).Error; err != nil {
		return err
	}

	log := entity.ReportLog{UserId: user.Id, Pid: report.Id, CreatedAt: report.ReportedAt, Type: util.TypeDevice}
	table := "report_log_" + strconv.Itoa(int(user.Id%10))
	db.Table(table).Create(&log)

	for key, value := range form.RiskDesc {
		db.Create(&entity.DeviceRiskDescAnnex{Pid: report.Id, Src: value, Type: key, AnnexType: 0})
	}

	for _, item := range form.RiskDescAnnexes {
		t, _ := strconv.Atoi(item["type"])
		db.Create(&entity.DeviceRiskDescAnnex{Pid: report.Id, Src: item["src"], Type: t, AnnexType: 1})
	}

	for key, value := range form.RiskAnalysis {
		db.Create(&entity.DeviceRiskAnalysisAnnex{Pid: report.Id, Src: value, Type: key, AnnexType: 0})
	}

	for _, item := range form.RiskAnalysisAnnexes {
		t, _ := strconv.Atoi(item["type"])
		db.Create(&entity.DeviceRiskAnalysisAnnex{Pid: report.Id, Src: item["src"], Type: t, AnnexType: 1})
	}

	//Id        uint   `gorm:"primary_key;AUTO_INCREMENT"`
	//Pid       uint   `gorm:"index"` // 关联 DeviceReport
	//Src       string `gorm:"size=255"`
	//Type      int
	//AnnexType int // 0 文本 1 图片 2 word 3 pdf

	return nil
}
